package com.tools.service.workflow.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.handler.StepHandlerManager;
import com.tools.pojo.workflow.bo.ExecutionPath;
import com.tools.pojo.workflow.bo.FlowNode;
import com.tools.pojo.workflow.bo.NodeExecutionResult;
import com.tools.pojo.workflow.bo.StepContext;
import com.tools.pojo.workflow.po.FlowDefinition;
import com.tools.pojo.workflow.po.FlowInstance;
import com.tools.pojo.workflow.po.FlowTransition;
import com.tools.pojo.workflow.po.StepExecution;
import com.tools.service.workflow.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class FlowEngineServiceImpl implements FlowEngineService {

    private final FlowDefinitionService flowDefinitionService;
    private final FlowInstanceService flowInstanceService;
    private final StepExecutionService stepExecutionService;
    private final StepHandlerManager stepHandlerManager;
    private final FlowNodeService flowNodeService;
    private final FlowTransitionService flowTransitionService;
    private final RedisTemplate<String, Object> redisTemplate;
    private final FlowRouterService flowRouterService;
    private final ObjectMapper objectMapper;

    private static final String FLOW_LOCK_PREFIX = "flow_lock:";
    private final ExpressionParser expressionParser = new SpelExpressionParser();

    /**
     * 启动流程（新版本）
     */
    @Transactional(rollbackFor = Exception.class)
    public Long startFlow(String flowCode, String businessKey, Map<String, Object> initialData) {
        // 获取流程定义
        FlowDefinition flowDefinition = flowDefinitionService.getByCode(flowCode);
        if (flowDefinition == null) {
            throw new RuntimeException("流程定义不存在: " + flowCode);
        }

        // 优先从缓存获取节点信息
        List<FlowNode> nodes = getNodesFromCache(flowDefinition.getId());
        if (nodes == null || nodes.isEmpty()) {
            // 缓存未命中，从数据库获取
            nodes = flowNodeService.getNodesByFlowDefinitionId(flowDefinition.getId());
            if (nodes.isEmpty()) {
                throw new RuntimeException("流程节点未定义: " + flowCode);
            }
        }

        // 创建流程实例，记录使用的流程定义版本
        FlowInstance flowInstance = flowInstanceService.createInstance(
                flowDefinition.getId(), businessKey, initialData);
        // 记录流程定义版本信息，确保执行过程中不受定义更新影响
        flowInstance.setFlowDefinitionVersion(flowDefinition.getVersion());
        flowInstanceService.updateById(flowInstance);

        // 创建步骤执行记录（只创建STEP类型的节点）
        List<StepExecution> stepExecutions = createStepExecutions(flowInstance.getId(), nodes);
        stepExecutionService.saveBatch(stepExecutions);

        log.info("流程启动成功，实例ID: {}, 使用流程定义版本: {}", flowInstance.getId(), flowDefinition.getVersion());
        return flowInstance.getId();
    }
    
    /**
     * 从缓存获取流程节点信息
     */
    private List<FlowNode> getNodesFromCache(Long definitionId) {
        try {
            String cacheKey = "flow:nodes:" + definitionId;
            return (List<FlowNode>) redisTemplate.opsForValue().get(cacheKey);
        } catch (Exception e) {
            log.warn("从缓存获取节点信息失败，将从数据库获取", e);
            return null;
        }
    }
    
    /**
     * 从缓存获取流程连线信息
     */
    private List<FlowTransition> getTransitionsFromCache(Long definitionId) {
        try {
            String cacheKey = "flow:transitions:" + definitionId;
            return (List<FlowTransition>) redisTemplate.opsForValue().get(cacheKey);
        } catch (Exception e) {
            log.warn("从缓存获取连线信息失败，将从数据库获取", e);
            return null;
        }
    }

    /**
     * 执行流程（新版本 - 基于节点和连线）
     */
    @Transactional(rollbackFor = Exception.class)
    public void executeFlow(Long flowInstanceId) {
        String lockKey = FLOW_LOCK_PREFIX + flowInstanceId;

        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 30, TimeUnit.SECONDS);
        if (Boolean.FALSE.equals(locked)) {
            throw new RuntimeException("流程正在执行中，请稍后重试");
        }

        long startTimeMs = System.currentTimeMillis(); // 记录流程执行开始时间
        
        try {
            FlowInstance flowInstance = flowInstanceService.getById(flowInstanceId);
            if (flowInstance == null) {
                throw new RuntimeException("流程实例不存在");
            }
            
            // 设置流程开始时间（如果尚未设置）
            if (flowInstance.getStartTime() == null) {
                flowInstance.setStartTime(LocalDateTime.now());
                flowInstanceService.updateById(flowInstance);
            }

            // 获取流程定义和节点信息
            Long flowDefinitionId = flowInstance.getFlowDefinitionId();
            Integer flowDefinitionVersion = flowInstance.getFlowDefinitionVersion();
            
            // 优先从缓存获取节点和连线信息
            List<FlowNode> nodes = getNodesFromCache(flowDefinitionId);
            if (nodes == null) {
                nodes = flowNodeService.getNodesByFlowDefinitionId(flowDefinitionId);
            }
            
            List<FlowTransition> transitions = getTransitionsFromCache(flowDefinitionId);
            if (transitions == null) {
                transitions = flowTransitionService.getTransitionsByFlowDefinitionId(flowDefinitionId);
            }
            
            log.info("执行流程实例: {}, 使用流程定义版本: {}", flowInstanceId, flowDefinitionVersion);

            // 构建节点映射
            Map<String, FlowNode> nodeMap = new HashMap<>();
            for (FlowNode node : nodes) {
                nodeMap.put(node.getNodeCode(), node);
            }

            // 构建连线映射
            Map<String, List<FlowTransition>> transitionMap = new HashMap<>();
            for (FlowTransition transition : transitions) {
                transitionMap.computeIfAbsent(transition.getSourceNode(), k -> new ArrayList<>())
                        .add(transition);
            }
            
            // 初始化共享上下文
            StepContext sharedContext = buildSharedContext(flowInstance);
            flowInstance.setSharedContext(sharedContext);

            // 执行流程
            executeFlowByNodes(flowInstance, nodeMap, transitionMap);

            // 检查流程是否完成
            checkAndUpdateFlowStatus(flowInstanceId);
            
            // 计算并更新流程执行时间
            long endTimeMs = System.currentTimeMillis();
            long executionDuration = endTimeMs - startTimeMs;
            
            // 更新流程实例时间信息
            flowInstance = flowInstanceService.getById(flowInstanceId);
            if (flowInstance != null) {
                flowInstance.setEndTime(LocalDateTime.now());
                flowInstance.setExecutionDuration(executionDuration);
                flowInstanceService.updateById(flowInstance);
                
                // 将执行时间信息保存到上下文数据中
                Map<String, Object> contextData = flowInstance.parseContextData();
                contextData.put("flowStartTime", startTimeMs);
                contextData.put("flowEndTime", endTimeMs);
                contextData.put("flowExecutionDuration", executionDuration);
                flowInstanceService.updateContextData(flowInstanceId, contextData);
                
                log.info("流程执行完成，实例ID: {}, 总耗时: {}毫秒", flowInstanceId, executionDuration);
            }

        } finally {
            redisTemplate.delete(lockKey);
        }
    }

    /**
     * 基于节点和连线的流程执行（更新版）
     */
    private void executeFlowByNodes(FlowInstance flowInstance, Map<String, FlowNode> nodeMap, Map<String, List<FlowTransition>> transitionMap) {

        String currentNodeCode = flowInstance.getCurrentNodeCode();
        if (currentNodeCode == null) {
            currentNodeCode = "START";
        }

        Set<String> executedNodes = new HashSet<>();

        while (currentNodeCode != null && !"END".equals(currentNodeCode)) {
            if (executedNodes.contains(currentNodeCode)) {
                log.warn("检测到循环执行，节点: {}", currentNodeCode);
                break;
            }

            FlowNode currentNode = nodeMap.get(currentNodeCode);
            if (currentNode == null) {
                log.error("节点不存在: {}", currentNodeCode);
                break;
            }

            executedNodes.add(currentNodeCode);

            // 记录节点开始执行（使用修复后的方法）
            try {
                flowInstanceService.recordNodeStart(
                        flowInstance.getId(),
                        currentNodeCode,
                        currentNode.getNodeName(),
                        currentNode.getNodeType()
                );
            } catch (Exception e) {
                log.error("记录节点开始执行失败: {}", currentNodeCode, e);
                // 继续执行，不中断流程
            }

            log.info("执行节点: {}[{}]", currentNode.getNodeName(), currentNode.getNodeType());

            // 执行当前节点
            NodeExecutionResult result = executeNode(flowInstance, currentNode);

            // 记录节点执行完成（使用修复后的方法）
            try {
                flowInstanceService.recordNodeComplete(
                        flowInstance.getId(),
                        currentNodeCode,
                        result.isSuccess(),
                        result.getMessage(),
                        result.getData()
                );
            } catch (Exception e) {
                log.error("记录节点执行完成失败: {}", currentNodeCode, e);
                // 继续执行，不中断流程
            }

            if (!result.isSuccess()) {
                log.error("节点执行失败: {}", currentNodeCode);
                handleNodeFailure(flowInstance, currentNode, result);
                break;
            }

            // 更新内存中的flowInstance对象，确保后续节点使用最新的上下文数据
            flowInstance = flowInstanceService.getById(flowInstance.getId());
            if (flowInstance == null) {
                log.error("流程实例不存在，可能已被删除");
                break;
            }
            
            // 重新设置共享上下文
            StepContext sharedContext = flowInstance.getSharedContext();
            if (sharedContext != null) {
                sharedContext.refreshFromFlowInstance(flowInstance);
            }

            // 使用路由服务获取下一个节点
            String nextNodeCode = flowRouterService.getNextNode(
                    flowInstance, currentNodeCode, transitionMap, result);

            // 验证路由是否有效
            if (nextNodeCode != null && !flowRouterService.validateNodeRoute(
                    flowInstance, currentNodeCode, nextNodeCode, transitionMap)) {
                log.error("无效的路由: {} -> {}", currentNodeCode, nextNodeCode);
                break;
            }

            currentNodeCode = nextNodeCode;
        }

        // 结束流程处理
        handleFlowCompletion(flowInstance, currentNodeCode, nodeMap);
    }

    /**
     * 处理节点执行失败
     */
    private void handleNodeFailure(FlowInstance flowInstance, FlowNode failedNode,
                                   NodeExecutionResult result) {

        // 更新流程状态为失败
        flowInstanceService.updateStatus(flowInstance.getId(), 2);

        // 记录失败信息到上下文
        Map<String, Object> failureContext = new HashMap<>();
        failureContext.put("failedNode", failedNode.getNodeCode());
        failureContext.put("failureTime", System.currentTimeMillis());
        failureContext.put("failureMessage", result.getMessage());
        flowInstanceService.updateContextData(flowInstance.getId(), failureContext);

        log.error("流程执行失败，节点: {}, 原因: {}",
                failedNode.getNodeCode(), result.getMessage());
    }

    /**
     * 处理流程完成
     */
    private void handleFlowCompletion(FlowInstance flowInstance, String finalNodeCode,
                                      Map<String, FlowNode> nodeMap) {

        if ("END".equals(finalNodeCode)) {
            // 执行结束节点
            FlowNode endNode = nodeMap.get("END");
            if (endNode != null) {
                flowInstanceService.recordNodeStart(flowInstance.getId(), "END", "结束", "END");
                flowInstanceService.recordNodeComplete(
                        flowInstance.getId(), "END", true, "流程执行完成", null);
            }

            log.info("流程执行完成，实例ID: {}", flowInstance.getId());
            flowInstanceService.updateStatus(flowInstance.getId(), 1); // 完成

            // 执行流程完成后的处理
            handlePostFlowCompletion(flowInstance);
        } else {
            log.warn("流程执行异常终止，最后节点: {}", finalNodeCode);
            flowInstanceService.updateStatus(flowInstance.getId(), 2); // 失败
        }
    }

    /**
     * 流程完成后的处理
     */
    private void handlePostFlowCompletion(FlowInstance flowInstance) {
        try {
            // 获取执行路径和结果
            ExecutionPath executionPath = flowInstanceService.getExecutionPath(flowInstance.getId());
            Map<String, Object> contextData = flowInstanceService.parseContextData(flowInstance.getContextData());

            // 生成执行报告
            generateFlowExecutionReport(flowInstance, executionPath, contextData);

            // 发送通知（如果需要）
            sendCompletionNotification(flowInstance, executionPath);

            log.info("流程后处理完成，实例ID: {}", flowInstance.getId());

        } catch (Exception e) {
            log.error("流程后处理失败", e);
        }
    }

    /**
     * 生成流程执行报告
     */
    private void generateFlowExecutionReport(FlowInstance flowInstance,
                                             ExecutionPath executionPath,
                                             Map<String, Object> contextData) {

        // 计算执行统计
        long totalTime = calculateTotalExecutionTime(executionPath);
        int successNodes = countSuccessNodes(executionPath);
        int totalNodes = executionPath.getTotalNodes();

        // 构建报告
        Map<String, Object> report = new HashMap<>();
        report.put("flowInstanceId", flowInstance.getId());
        report.put("businessKey", flowInstance.getBusinessKey());
        report.put("totalExecutionTime", totalTime);
        report.put("successRate", totalNodes > 0 ? (double) successNodes / totalNodes * 100 : 0);
        report.put("nodeExecutionDetails", executionPath.getNodes());
        report.put("completionTime", System.currentTimeMillis());

        // 保存报告到上下文
        contextData.put("executionReport", report);
        flowInstanceService.updateContextData(flowInstance.getId(), contextData);

        log.info("流程执行报告生成完成，实例ID: {}", flowInstance.getId());
    }

    /**
     * 计算总执行时间
     */
    private long calculateTotalExecutionTime(ExecutionPath executionPath) {
        if (executionPath.getNodes().isEmpty()) {
            return 0;
        }

        // 简化实现，实际应该解析时间字符串计算差值
        return executionPath.getNodes().size() * 1000L; // 模拟值
    }

    /**
     * 计算成功节点数
     */
    private int countSuccessNodes(ExecutionPath executionPath) {
        return (int) executionPath.getNodes().stream()
                .filter(node -> Boolean.TRUE.equals(node.getSuccess()))
                .count();
    }

    /**
     * 发送完成通知
     */
    private void sendCompletionNotification(FlowInstance flowInstance, ExecutionPath executionPath) {
        // 实现通知逻辑，如发送邮件、消息等
        log.info("发送流程完成通知，实例ID: {}", flowInstance.getId());
    }

    /**
     * 执行单个节点（返回详细结果）
     */
    private NodeExecutionResult executeNode(FlowInstance flowInstance, FlowNode node) {
        try {
            String nodeType = node.getNodeType();

            return switch (nodeType) {
                case "START" ->
                    // 开始节点，无需执行操作
                        NodeExecutionResult.success("开始节点");
                case "END" ->
                    // 结束节点
                        NodeExecutionResult.success("结束节点");
                case "STEP" ->
                    // 步骤节点，执行步骤处理器
                        executeStepNode(flowInstance, node);
                case "CONDITION" ->
                    // 条件分支节点，评估条件
                        executeConditionNode(flowInstance, node);
                default -> {
                    log.warn("未知节点类型: {}", nodeType);
                    yield NodeExecutionResult.failure("未知节点类型: " + nodeType);
                }
            };

        } catch (Exception e) {
            log.error("节点执行失败: {}[{}]", node.getNodeName(), node.getNodeType(), e);
            return NodeExecutionResult.failure("节点执行异常: " + e.getMessage());
        }
    }

    /**
     * 执行步骤节点
     */
    private NodeExecutionResult executeStepNode(FlowInstance flowInstance, FlowNode node) {
        try {
            // 创建或更新步骤执行记录
            StepExecution stepExecution = createOrUpdateStepExecution(flowInstance.getId(), node);

            // 获取步骤处理器
            StepHandler stepHandler = stepHandlerManager.getHandler(node.getNodeCode());
            if (stepHandler == null) {
                throw new RuntimeException("未找到步骤处理器: " + node.getNodeCode());
            }

            // 构建步骤上下文
            StepContext context = buildStepContext(flowInstance, node, stepExecution);
            // 同步最新上下文数据
            context.refreshFromFlowInstance(flowInstance);  // 需要新增同步方法


            // 执行步骤
            Result<?> result = stepHandler.execute(context);

            // 持久化更新后的上下文
            flowInstanceService.updateContextData(
                    flowInstance.getId(),
                    context.getContextData()  // 获取最新数据
            );


            // 更新步骤执行结果
            updateStepExecutionResult(stepExecution, result, context);

            return NodeExecutionResult.fromStepResult(result);

        } catch (Exception e) {
            log.error("步骤节点执行失败: {}", node.getNodeCode(), e);
            return NodeExecutionResult.failure("步骤执行异常: " + e.getMessage());
        }
    }

    // 新增共享上下文构建方法
    private StepContext buildSharedContext(FlowInstance flowInstance) {
        StepContext context = new StepContext();
        context.setFlowInstanceId(flowInstance.getId());
        context.setContextData(flowInstanceService.parseContextData(flowInstance.getContextData()));
        return context;
    }


    /**
     * 执行条件分支节点
     */
    private NodeExecutionResult executeConditionNode(FlowInstance flowInstance, FlowNode node) {
        try {
            // 条件分支节点主要是在getNextNode中评估条件
            // 这里只是记录执行成功，实际的条件评估在路由逻辑中处理



            return NodeExecutionResult.success("条件分支节点执行完成");
        } catch (Exception e) {
            log.error("条件分支节点执行失败: {}", node.getNodeCode(), e);
            return NodeExecutionResult.failure("条件分支节点执行异常: " + e.getMessage());
        }
    }


    /**
     * 获取下一个节点
     */
    private String getNextNode(FlowInstance flowInstance, String currentNodeCode,
                               Map<String, List<FlowTransition>> transitionMap) {

        List<FlowTransition> outTransitions = transitionMap.get(currentNodeCode);
        if (outTransitions == null || outTransitions.isEmpty()) {
            return null;
        }

        // 如果是条件分支节点，需要评估条件
        FlowNode currentNode = flowNodeService.getNodeByCode(flowInstance.getFlowDefinitionId(), flowInstance.getCurrentNodeCode());
        if (currentNode != null && "CONDITION".equals(currentNode.getNodeType())) {
            return evaluateConditionTransitions(flowInstance, outTransitions);
        }

        // 对于其他节点，返回第一个默认连线或无条件连线
        for (FlowTransition transition : outTransitions) {
            if ("DEFAULT".equals(transition.getTransitionType())) {
                return transition.getTargetNode();
            }
        }

        // 如果没有默认连线，返回第一个连线的目标节点
        return outTransitions.get(0).getTargetNode();
    }

    /**
     * 评估条件连线
     */
    private String evaluateConditionTransitions(FlowInstance flowInstance, List<FlowTransition> transitions) {
        // 创建SPEL评估上下文
        StandardEvaluationContext spelContext = new StandardEvaluationContext();

        // 获取流程上下文数据
        Map<String, Object> contextData = flowInstanceService.parseContextData(flowInstance.getContextData());
        for (Map.Entry<String, Object> entry : contextData.entrySet()) {
            spelContext.setVariable(entry.getKey(), entry.getValue());
        }

        // 按优先级评估条件
        for (FlowTransition transition : transitions) {
            if ("DEFAULT".equals(transition.getTransitionType())) {
                // 默认连线，直接返回
                return transition.getTargetNode();
            }

            if ("CONDITION".equals(transition.getTransitionType())) {
                String conditionExpr = transition.getConditionExpression();
                if (conditionExpr == null || conditionExpr.trim().isEmpty()) {
                    continue;
                }

                try {
                    Expression expression = expressionParser.parseExpression(conditionExpr);
                    Boolean result = expression.getValue(spelContext, Boolean.class);

                    if (Boolean.TRUE.equals(result)) {
                        log.info("条件满足: {} -> {}", conditionExpr, transition.getTargetNode());
                        return transition.getTargetNode();
                    }
                } catch (Exception e) {
                    log.warn("条件表达式评估失败: {}, 错误: {}", conditionExpr, e.getMessage());
                }
            }
        }

        // 如果没有条件满足，返回最后一个连线的目标节点（通常是默认分支）
        return transitions.get(transitions.size() - 1).getTargetNode();
    }

    /**
     * 创建或更新步骤执行记录
     */
    private StepExecution createOrUpdateStepExecution(Long flowInstanceId, FlowNode node) {
        StepExecution execution = stepExecutionService.getByFlowInstanceAndStepCode(flowInstanceId, node.getNodeCode());

        if (execution == null) {
            execution = new StepExecution();
            execution.setFlowInstanceId(flowInstanceId);
            execution.setStepCode(node.getNodeCode());
            execution.setStepName(node.getNodeName());
            execution.setExecuteOrder(node.getExecuteOrder());
            execution.setStatus(0); // 待执行
            execution.setCreateTime(LocalDateTime.now());
            stepExecutionService.save(execution);
        }

        // 更新为执行中状态
        execution.setStatus(1); // 执行中
        execution.setStartTime(LocalDateTime.now());
        stepExecutionService.updateById(execution);

        return execution;
    }

    /**
     * 构建步骤上下文
     */
    private StepContext buildStepContext(FlowInstance flowInstance, FlowNode node, StepExecution stepExecution) {
        StepContext context = new StepContext();
        context.setFlowInstanceId(flowInstance.getId());
        context.setBusinessKey(flowInstance.getBusinessKey());
        context.setCurrentStep(node.getNodeCode());

        // 从流程实例中加载上下文数据
        Map<String, Object> contextData = flowInstanceService.parseContextData(flowInstance.getContextData());
        context.setContextData(contextData);

        // 解析节点配置
        Map<String, Object> nodeConfig = parseNodeConfig(node.getConfig());
        context.setStepConfig(nodeConfig);

        return context;
    }

    /**
     * 更新步骤执行结果
     */
    private void updateStepExecutionResult(StepExecution stepExecution, Result<?> result, StepContext context) {
        stepExecution.setEndTime(LocalDateTime.now());

        if (result.isSuccess()) {
            stepExecution.setStatus(2); // 成功
            stepExecution.setOutputData(serializeOutputData(result.getData()));

            // 更新流程上下文数据
            if (result.getData() != null) {
                flowInstanceService.updateContextData(
                        stepExecution.getFlowInstanceId(),
                        context.getContextData()
                );
            }
        } else {
            stepExecution.setStatus(3); // 失败
            stepExecution.setErrorMessage(result.getMessage());
        }

        stepExecutionService.updateById(stepExecution);
    }

    /**
     * 创建步骤执行记录
     */
    private List<StepExecution> createStepExecutions(Long flowInstanceId, List<FlowNode> nodes) {
        List<StepExecution> executions = new ArrayList<>();

        for (FlowNode node : nodes) {
            if ("STEP".equals(node.getNodeType())) {
                StepExecution execution = new StepExecution();
                execution.setFlowInstanceId(flowInstanceId);
                execution.setStepCode(node.getNodeCode());
                execution.setStepName(node.getNodeName());
                execution.setExecuteOrder(node.getExecuteOrder());
                execution.setStatus(0); // 待执行
                execution.setCreateTime(LocalDateTime.now());
                executions.add(execution);
            }
        }

        return executions;
    }

    /**
     * 解析节点配置
     */
    private Map<String, Object> parseNodeConfig(String configJson) {
        try {
            if (configJson == null || configJson.trim().isEmpty()) {
                return new HashMap<>();
            }
            // 使用注入的objectMapper进行解析
            return objectMapper.readValue(configJson, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("解析节点配置失败", e);
            return new HashMap<>();
        }
    }

    /**
     * 序列化输出数据
     */
    private String serializeOutputData(Object outputData) {
        try {
            if (outputData == null) {
                return "{}";
            }
            
            // 使用已配置的ObjectMapper正确序列化JSON，包含Java 8日期时间类型支持
            String json = objectMapper.writeValueAsString(outputData);
            
            // 如果JSON数据过大，可以考虑截取或压缩
            if (json.length() > 10000) { // 假设数据库字段有限制
                log.warn("输出数据过大，长度: {}", json.length());
                // 返回简化版，避免数据截断
                return objectMapper.writeValueAsString(Map.of(
                    "type", outputData.getClass().getSimpleName(),
                    "message", "数据过大，已简化处理"
                ));
            }
            
            return json;
        } catch (Exception e) {
            log.error("序列化输出数据失败", e);
            return "{}";
        }
    }

    /**
     * 检查并更新流程状态
     */
    private void checkAndUpdateFlowStatus(Long flowInstanceId) {
        List<StepExecution> steps = stepExecutionService.getByFlowInstanceId(flowInstanceId);

        boolean allSuccess = steps.stream().allMatch(step -> step.getStatus() == 2);
        boolean hasFailure = steps.stream().anyMatch(step -> step.getStatus() == 3);

        if (allSuccess) {
            flowInstanceService.updateStatus(flowInstanceId, 1); // 完成
        } else if (hasFailure) {
            flowInstanceService.updateStatus(flowInstanceId, 2); // 失败
        }
    }
}
